<?php

require_once 'Mysql.php';

class Membership {
	
	function validate_user($un, $pwd) {
		$mysql = New Mysql();
		$ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);
		
		if($ensure_credentials) {
			$_SESSION['status'] = 'authorized';
			header("location: index.php");
		} else return "Please enter a correct username and password";
		
	} 
	
	    // submit the information of user
    function submit_user_data($userID,$fname,$lname,$mi,$address,$SYear,$SMonth,$SDay,$phone,$opwd,$npwd,$npwd2,$email){
		$pwd = "";
		$return_val = "";
		$mysql = New Mysql();
		echo "submit user data: '".$opwd."' ";
		if($opwd != ""){
			echo "will check pw";
			$validPassword = $mysql->verify_Username_and_Pass($_SESSION['username'], $opwd);
			if($validPassword){
				if($npwd != $npwd2){
					return "New Passwords are not Equal";
				} else {
					$mysql->set_pwd($_SESSION['username'],$npwd);
					$return_val .= "Password Set - ";					
				}
			} else {
				return "Invalid Password";
			}
		}
	
		$dob = $SYear."-".$SMonth."-".$SDay;    		
		$submit_user_data = $mysql->submit_user_data($userID,$fname,$lname,$mi,$address,$dob,$phone,$email);
		$return_val .= "Settings Updated";
		return $return_val;
    	
    }
	
    function register_user($un, $pwd, $pwd2, $email) {
		//Verify Passwords are equal
        if($pwd != $pwd2){
            return "Passwords are not Equal";
        }
        //TODO: Verify Valid email
        
        //Verify Username is not taken
        $mysql = New Mysql();
        $unused_username = $mysql->verify_unused_username($un);
        if($unused_username) {
			$registered_user = $mysql->register_user($un,$pwd,$email);
            if($registered_user){
                header("location: login.php");
            } else return "Failed to add user";
		} else return "Username already in use.";
		
	} 
    
	function log_User_Out() {
		if(isset($_SESSION['status'])) {
            $_SESSION['status'] = 'unauth';
			unset($_SESSION['status']);
			
			if(isset($_COOKIE[session_name()])) 
				setcookie(session_name(), '', time() - 1000);
				session_destroy();
		}
	}
	
	function confirm_Member() {
		session_start();
		if($_SESSION['status'] !='authorized') header("location: login.php");
	}
    
    function isAuth() {
		if($_SESSION['status'] = 'authorized') return true;
	}
    
	
}